#include <sensor.h>
#include <controller.h>
#include <user.h>
#include <defs.h>
#include <string.h>
#include <io.h>
#include <iobuf.h>

int PollSensors(char *last, char *curr, char track) {
  int i, c, T, diff;
  int sum;
  Wh();
  i = 0; T = 0;
  while (i < 10 && T < 5) {
    if (Hasc(COM1)) {
      c = Getc(COM1);
      last[i] = curr[i];
      curr[i] = c;
      i++;
    } else {
      Delay(1);
      T++;
    }
  }

  if (i == 10) {
    diff = FALSE; sum = FALSE;
    for (i = 0; i < 10; i++) {
      sum |= curr[i];
      diff |= curr[i] != last[i];
    }
    return diff && sum;
  }
  return FALSE;
}

void SensorManager() {
  char track;
  
  int i;
  char last[10];
  char curr[10];
  for (i = 0; i < 10; i++) {
    last[i] = 0x00;
    curr[i] = 0x00;
  }

  int parent_tid;
  Receive(&parent_tid, &track, 1);
  Reply(parent_tid, NULL, 0);
  PrintAt(1, 24, "track: %c\r\n", track);
  
  for ( ; ; ) {
    Delay(1);
    if (PollSensors(last, curr, track))
      NotifyEvent(EVENT_NEW_SENSOR, curr, 10);
  }
  Panic("SensorManager", "Chuck Norris!");
}
